import { store } from './store.js';

//============================hash前端路由
/*
* 夕空 flashme.cn 2024-3-9
//初始化
window.Router = new Router();
window.Router.init();
//方法
Router.route("home", 触发函数, 退出函数);
填写"hash"将会监听每次地址变更的触发

#可多个路由挂载一个事件
  Router.route(["home","list",...], function, function)
#多个打开路由
  location.hash = '#/home/sub';
#打开此路由已打开的路由页面不退出
  Router.routes['sub1'].sub = true;
*/
function Router() {
    this.routes = {};
    this.currentUrl = '';
}
Router.prototype.route = function (path, callback, removeback) {
    var obj = { start: false };
    obj.callback = callback || function () { };
    if (removeback) obj.leave = removeback;
    if(path instanceof Array){
        for(var i in path){
            this.routes[path[i]] = obj;
        }
    }else{
        this.routes[path] = obj;
    }
};
Router.prototype.refresh = function (ev) {

    const currentUrl = location.hash.slice(1).split("?")[0] || '/home';
    if(currentUrl.slice(0,1)!="/"){
        return;
    }
    this.currentUrl = currentUrl.slice(1);
    var hash = this.currentUrl.split("/");
    this.routes["hash"] && this.routes["hash"].callback(hash, currentUrl, ev);
    var beforeUrl = false;
    for(var i in hash){
        var _hash = this.routes[hash[i]];
        if (_hash) {
            if(_hash.start == false){
                _hash.callback(hash[i], ev);
                _hash.start = true;
            }
            _hash.sub && (beforeUrl = true);
        }
    }

    if(beforeUrl){
        return;
    }
    //在判断全部地址是否执行退出
    for (var k in this.routes) {
        var than = this.routes[k];
        if (than.start && hash.indexOf(k) == -1) {
            than.start = false;
            than.leave && than.leave(k);
        }
    }

};

Router.prototype.init = function () {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
}


//解析地址栏参数 new getUrlSearch()
//new getUrlSearch(true) 将会解析#后面参数
function getUrlSearch(hash) {
    var name, value;
    var str = location.href.split("#");
    str = (hash && str.length>1) ? str[1] : str[0];
    str = str.substring(str.indexOf("?") + 1);
    var arr = str.split("&");
    for (var i = 0; i < arr.length; i++) {
        var num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = decodeURI(arr[i].substring(num + 1));
            this[name] = value;
        }
    }
}
//Object转地址栏参数
function obj2Param(obj) {
    return Object.keys(obj).map(key => {
        return key + '=' + obj[key]
    }).join('&')
}

//页面跳转，向页面传参
function topage(url, params) {
    params && params.pTitle && (store.title = params.pTitle)
    store.pageParams = params || {};
    window.location.hash = '#' + url;
}

export {
	Router,getUrlSearch,obj2Param,topage
};